package com.cn.kabalifemerchants.ui;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.cn.kabalifemerchants.R;
import com.cn.kabalifemerchants.base.IBaseActivity;
import com.cn.kabalifemerchants.config.LoginHelper;
import com.cn.kabalifemerchants.ui.hall.FragmenHall;
import com.cn.kabalifemerchants.ui.order.FragmentOrder;
import com.cn.kabalifemerchants.ui.page.FragmentPage;
import com.cn.kabalifemerchants.ui.recruit.FragmentRecruit;
import com.cn.kabalifemerchants.ui.user.FragmentUser;
import com.cn.kabalifemerchants.utils.ExampleUtil;
import com.cn.kabalifemerchants.utils.PermissionsUtils;
import com.cn.kabalifemerchants.utils.RxToast;
import com.cn.kabalifemerchants.utils.SPUtil;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends IBaseActivity<MainActivityView, MainActivityPresenter> implements MainActivityView {

    @BindView(R.id.fragmentContent)
    FrameLayout fragmentContent;


    @BindColor(R.color.text_909090)
    int normalColor;
    @BindColor(R.color.main_color)
    int selectedColor;
    @BindView(R.id.text_service)
    TextView textService;
    @BindView(R.id.text_integral)
    TextView textIntegral;
    @BindView(R.id.text_release)
    TextView textRelease;
    @BindView(R.id.text_order)
    TextView textOrder;
    @BindView(R.id.text_me)
    TextView textMe;


    private long exitTime = 0;//标记退出时间。

    private FragmentPage page;
    private FragmentRecruit recruit;
    private FragmenHall hall;
    private FragmentOrder order;
    private FragmentUser my;


    private final String TAG_FRAGMENT_PSERVICE = "page";
    private final String TAG_FRAGMENT_INTEGRAL = "recruit";
    private final String TAG_FRAGMENT_RELEASE = "hall";
    private final String TAG_FRAGMENT_ORDER = "order";
    private final String TAG_FRAGMENT_MY = "my";
    /**
     * 用户选中的fragment的tag
     */
    private String selectedFragmentTag;
    private FragmentManager fragmentManager;

    @Override
    protected MainActivityPresenter createPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void beforeInitView() {
        super.beforeInitView();
        mImmersionBar.statusBarDarkFont(true).init();
    }

    //极光推送需要的
    public static boolean isForeground = false;

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.cn.kabalifemerchants.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";


    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
//                    setCostomMsg(showMsg.toString());
                    RxToast.success(context.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onReLoggedIn(String msg) {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public Context _getContext() {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
//        initDrawable(); //图标切换
        SPUtil.saveString(LoginHelper.IS_GUIDE_PAGE, "1");
        SPUtil.saveString(LoginHelper.IS_GUIDE_Age, "1");
        String str = LoginHelper.getUserData().getResult().getId() + "2";
        JPushInterface.setAlias(getMe(), 1, str);
        fragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            page = (FragmentPage) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_PSERVICE);
            recruit = (FragmentRecruit) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_INTEGRAL);
            hall = (FragmenHall) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_RELEASE);
            order = (FragmentOrder) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_ORDER);
            my = (FragmentUser) fragmentManager
                    .findFragmentByTag(TAG_FRAGMENT_MY);

            selectedFragmentTag = savedInstanceState.getString("tag");
        }

        //默认选中主页
        selectedFragmentTag = TAG_FRAGMENT_PSERVICE;


        setSelectedFragment(selectedFragmentTag);
        setSelectedIcon(selectedFragmentTag);
//        boolean str = PermissionsUtils.isAppliedPermission(this,
//                Manifest.permission.ACCESS_FINE_LOCATION);
//        if (str == false) {
//            //        //动态获取权限。
//            if (Build.VERSION.SDK_INT > 23) {
//                MainActivityPermissionsDispatcher.initPermissionWithCheck(this);
//            }
//        }


//        Set<String> set = new HashSet<>();
//        set.add("meridian_health_reminder");
//        set.add("solar_reminder");
//        set.add("four_seasons_reminder");
//        set.add("fitness_reminder");
//        JPushInterface.setTags(getMe(), 4, set);

    }


    /**
     * add添加
     *
     * @param fragment
     * @param tag
     */
    private void addFragment(Fragment fragment, String tag) {
        fragmentManager.beginTransaction().add(R.id.fragmentContent, fragment, tag).commit();
    }

    /**
     * 显示与隐藏
     *
     * @param fragment
     */
    private void showFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //先隐藏所有的fragment
        if (page != null) {
            transaction.hide(page);
        }
        if (recruit != null) {
            transaction.hide(recruit);
        }
        if (hall != null) {
            transaction.hide(hall);
        }
        if (order != null) {
            transaction.hide(order);
        }
        if (my != null) {
            transaction.hide(my);
        }
        transaction.show(fragment).commit();
        selectedFragmentTag = fragment.getTag();
    }

    private void setSelectedFragment(String selectedFragmentTag) {
        switch (selectedFragmentTag) {
            case TAG_FRAGMENT_PSERVICE:
                if (page == null) {
                    page = new FragmentPage();
                    addFragment(page, TAG_FRAGMENT_PSERVICE);
                }
                showFragment(page);
                break;
            case TAG_FRAGMENT_INTEGRAL:
                if (recruit == null) {
                    recruit = new FragmentRecruit();
                    addFragment(recruit, TAG_FRAGMENT_INTEGRAL);
                }
                showFragment(recruit);
                break;
            case TAG_FRAGMENT_RELEASE:
                if (hall == null) {
                    hall = new FragmenHall();
                    addFragment(hall, TAG_FRAGMENT_RELEASE);
                }
                showFragment(hall);
                break;
            case TAG_FRAGMENT_ORDER:
                if (order == null) {
                    order = new FragmentOrder();
                    addFragment(order, TAG_FRAGMENT_ORDER);
                }
                showFragment(order);
                break;
            case TAG_FRAGMENT_MY:
                if (my == null) {
                    my = new FragmentUser();
                    addFragment(my, TAG_FRAGMENT_MY);
                }
                showFragment(my);
                break;

            default:
                break;
        }
    }

    /**
     * 清除导航栏所有的选中状态。
     */
    private void clearSelection() {
        textIntegral.setTextColor(normalColor);
        textService.setTextColor(normalColor);
        textRelease.setTextColor(normalColor);
        textOrder.setTextColor(normalColor);
        textMe.setTextColor(normalColor);
    }

    public void setSelectedIcon(String selectedIcon) {
        clearSelection();  //TODO 先清除所有状态
        switch (selectedIcon) {
            case TAG_FRAGMENT_PSERVICE:
                textService.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_INTEGRAL:
                textIntegral.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_RELEASE:
                textRelease.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_ORDER:
                textOrder.setTextColor(selectedColor);
                break;
            case TAG_FRAGMENT_MY:
                textMe.setTextColor(selectedColor);
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.layout_service, R.id.layout_integral, R.id.layout_release, R.id.layout_order, R.id.layout_me})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_service:
                if (!TAG_FRAGMENT_PSERVICE.equals(selectedFragmentTag)) {
                    setSelectedFragment(TAG_FRAGMENT_PSERVICE);
                    setSelectedIcon(TAG_FRAGMENT_PSERVICE);
                }
                break;
            case R.id.layout_integral:
                if (!TAG_FRAGMENT_INTEGRAL.equals(selectedFragmentTag)) {
                    setSelectedFragment(TAG_FRAGMENT_INTEGRAL);
                    setSelectedIcon(TAG_FRAGMENT_INTEGRAL);
                }
                break;
            case R.id.layout_release:
                if (!TAG_FRAGMENT_RELEASE.equals(selectedFragmentTag)) {
                    setSelectedFragment(TAG_FRAGMENT_RELEASE);
                    setSelectedIcon(TAG_FRAGMENT_RELEASE);
                }
                break;
            case R.id.layout_order:
                if (!TAG_FRAGMENT_ORDER.equals(selectedFragmentTag)) {
                    setSelectedFragment(TAG_FRAGMENT_ORDER);
                    setSelectedIcon(TAG_FRAGMENT_ORDER);
                }
                break;
            case R.id.layout_me:
                if (!TAG_FRAGMENT_MY.equals(selectedFragmentTag)) {
                    setSelectedFragment(TAG_FRAGMENT_MY);
                    setSelectedIcon(TAG_FRAGMENT_MY);
                }
                break;
        }
    }

    /**
     * 退出
     */
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - exitTime) < 2000) {
            super.onBackPressed();
            finishAll();
            Process.killProcess(Process.myPid());
            Runtime.getRuntime().gc();
        } else {
            RxToast.success("再按一次退出程序");
            exitTime = currentTime;
        }
    }
}